package com.baosight.risk.common.quartz;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baosight.risk.mapper.quartz.SysSyncEmpleeMapper;
import com.baosight.risk.mapper.xtzy.XtzyOrgEhrMapper;
import com.baosight.risk.service.quartz.entity.SyncEmpleeEntitiy;
import com.baosight.risk.service.xtzy.entity.XtzyOrgEhr;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author lixuanhan
 * @date 2025-03-11 09:56:38
 * 类描述：宝武HR接口同步定时任务
 */
@Slf4j
@Component
public class BaowuHrTask {


    @Value("${baowuHR.systemCode}")
    private String systemCode;
    @Value("${baowuHR.license}")
    private String license;
    @Value("${baowuHR.authCode-url}")
    private String authCodeUrl;
    @Value("${baowuHR.empInfo-url}")
    public String empInfoUrl;
    @Value("${baowuHR.orgInfo-url}")
    public String orgInfoUrl;
    @Value("${baowuHR.dimissionInfo-url}")
    public String dimissionInfoUrl;


    @Autowired
    private XtzyOrgEhrMapper orgEhrMapper;

    @Autowired
    private SysSyncEmpleeMapper syncEmpleeMapper;

    /**
     * 获取bwhr授权码
     *
     * @return
     */
    public String getAuthCode() {
        HttpRequest request = HttpUtil.createPost(authCodeUrl);
        request.header("Content-Type", "application/json");
        JSONObject requestBody = new JSONObject();
        requestBody.put("systemCode", systemCode);
        requestBody.put("license", license);
        request.body(requestBody.toString());
        log.info("BWHR获取授权码接口发送请求，请求地址：" + authCodeUrl);
        // 发送请求并获取响应
        HttpResponse response = request.execute();
        log.info("BWHR获取授权码接口响应值：" + response);
        if (200 == response.getStatus()) {
            JSONObject jsonObject = JSONObject.parseObject(response.body());
            log.info("BWHR获取授权码接口请求成功返回数据：" + jsonObject);
            Boolean isSuccess = jsonObject.getBoolean("isSuccess");

            //接口调用成功
            if (isSuccess) {
                JSONObject data = jsonObject.getJSONObject("data");
                return data.getString("authCode");
            }
        }
        return null;
    }


    /**
     * 获取接口信息
     * JSON流
     *
     * @param authCode 授权码
     * @param portUrl  接口地址
     * @return
     * @throws IOException
     */
    public List<JSONObject> getInfoList(String authCode, String portUrl) throws IOException {
        HttpRequest request = HttpUtil.createPost(portUrl);
        request.header("Content-Type", "application/json");
        request.header("systemCode", systemCode);
        request.header("authCode", authCode);
        // 发送请求并获取响应
        HttpResponse response = request.execute();
        log.info("BWHR接口响应：" + response);
        // 获取响应状态码
        int statusCode = response.getStatus();

        List<JSONObject> baowuInfoList = new ArrayList<>();
        if (200 == statusCode) {
            // 获取响应的json流
            InputStream inputStream = response.bodyStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "GBK"));
            // 使用BufferedReader读取输入流
            String responseLine;
            // 逐行读取响应并追加到
            while ((responseLine = br.readLine()) != null) {
                // 将响应字符串转换为对象
                JSONObject o = JSONObject.parseObject(responseLine.trim());
                baowuInfoList.add(o);
            }

            return baowuInfoList;
        }
        return null;
    }

    /**
     * 拆分集合
     *
     * @param list 总集合
     * @param size 拆分集合的大小
     * @param <T>
     * @return
     */
    public static <T> List<List<T>> splitList(List<T> list, int size) {
        List<List<T>> result = new ArrayList<>();
        int listSize = list.size();

        for (int i = 0; i < listSize; i += size) {
            int toIndex = Math.min(listSize, i + size);
            result.add(new ArrayList<>(list.subList(i, toIndex)));
        }

        return result;
    }


    /**
     * 同步人员信息（BWHR）
     *
     * @param params
     * @param jobId
     */
    public void syncEmployee(String params, String jobId) {
        try {
            List<JSONObject> infoList = getInfoList(getAuthCode(), empInfoUrl);
            //清空机构临时表
            if (!infoList.isEmpty()) syncEmpleeMapper.deleteAll();
            List<SyncEmpleeEntitiy> empEhrList = new ArrayList<>();
            for (int i = 0; i < infoList.size(); i++) {
                JSONObject jsonObject = infoList.get(i);
                SyncEmpleeEntitiy syncEmpleeEntitiy = new SyncEmpleeEntitiy();
                syncEmpleeEntitiy.setEmpCode(jsonObject.getString("empCode"));
                syncEmpleeEntitiy.setEmpName(jsonObject.getString("empName"));
                syncEmpleeEntitiy.setOrgCode(jsonObject.getString("orgCode"));
                syncEmpleeEntitiy.setOrgName(jsonObject.getString("orgName"));
                syncEmpleeEntitiy.setEmail(jsonObject.getString("email"));
                syncEmpleeEntitiy.setPostName(jsonObject.getString("postName"));
                empEhrList.add(syncEmpleeEntitiy);
            }
            //拆分集合，每个集合大小为200
            List<List<SyncEmpleeEntitiy>> splitList = splitList(empEhrList, 200);
            //新增进入人员临时表
            splitList.forEach(list -> {
                syncEmpleeMapper.batchInsert(list);
            });
        }catch (Exception e){
            throw new RuntimeException(e);
        }

    }

    /**
     * 同步机构信息（BWHR）
     *
     * @param params
     * @param jobId
     */
    public void syncOrg(String params, String jobId) {
        try {
            List<JSONObject> infoList = getInfoList(getAuthCode(), orgInfoUrl);
            //清空机构临时表
            if (!infoList.isEmpty()) orgEhrMapper.deleteAll();

            List<XtzyOrgEhr> orgEhrList = new ArrayList<>();
            for (int i = 0; i < infoList.size(); i++) {
                JSONObject jsonObject = infoList.get(i);
                XtzyOrgEhr xtzyOrgEhr = new XtzyOrgEhr();
                xtzyOrgEhr.setOrgCode(jsonObject.getString("orgCode"));
                xtzyOrgEhr.setOrgName(jsonObject.getString("orgName"));
                xtzyOrgEhr.setTargetOrgCode(jsonObject.getString("parentOrgCode"));
                xtzyOrgEhr.setTargetOrgName(jsonObject.getString("parentOrgName"));
                xtzyOrgEhr.setOrgTypeId(jsonObject.getString("orgTypeId"));
                xtzyOrgEhr.setOrgType(jsonObject.getString("orgTypeName"));
                xtzyOrgEhr.setFromDate(jsonObject.getString("effectiveDate"));
                xtzyOrgEhr.setToDate("9999-12-31");
                xtzyOrgEhr.setAliveFlag("1");
                xtzyOrgEhr.setUseStatus("1");
                xtzyOrgEhr.setOrgFullName(jsonObject.getString("orgFullName"));
                orgEhrList.add(xtzyOrgEhr);
            }
            //拆分集合，每个集合大小为200
            List<List<XtzyOrgEhr>> splitList = splitList(orgEhrList, 200);
            //新增进入机构临时表
            splitList.forEach(list -> {
                orgEhrMapper.batchInsert(list);
            });
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
